using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Wpf_Scrcpy.MOD;
using Wpf_Scrcpy.Mothod;
using Mapster.Models;
using Mapster;
using System.Linq;
using Microsoft.Win32;
using System.Windows;
using Wpf_Scrcpy.Views;

namespace Wpf_Scrcpy.ViewModel
{
    /// <summary>
    /// This class contains properties that the main View can data bind to.
    /// </summary>
    public class MainViewModel : ViewModelBase
    {
        public List<COMMAND_data> datas1 = new List<COMMAND_data>();

        // 基本设置
        COMMAND_data _设备 = new COMMAND_data() { 命令 = "设备", 描述 = "使用 adb devices 列出了多个设备，则必须指定设备 序列号", 指令 = "--serial", 参数 = "", 启用 = true };
        public COMMAND_data 设备 { get => _设备; set => Set(ref _设备, value); }
        
        COMMAND_data _码率 = new COMMAND_data() { 命令 = "码率", 描述 = "默认编码器是 8Mbps，要更改视频编码器 (例如设为 1Mbps)", 指令 = "--video-bit-rate", 参数 = "8M", 启用 = true };
        public COMMAND_data 码率 { get => _码率; set => Set(ref _码率, value); }
        
        COMMAND_data _帧率 = new COMMAND_data() { 命令 = "帧率", 描述 = "", 指令 = "--max-fps", 参数 = "60", 启用 = true };
        public COMMAND_data 帧率 { get => _帧率; set => Set(ref _帧率, value); }
        
        COMMAND_data _分辨率 = new COMMAND_data() { 命令 = "分辨率", 描述 = "", 指令 = "--max-size", 参数 = "1080", 启用 = true };
        public COMMAND_data 分辨率 { get => _分辨率; set => Set(ref _分辨率, value); }
        
        COMMAND_data _画面裁剪 = new COMMAND_data() { 命令 = "画面裁剪", 描述 = "", 指令 = "--crop", 参数 = "1080:2000:0:0", 启用 = false };
        public COMMAND_data 画面裁剪 { get => _画面裁剪; set => Set(ref _画面裁剪, value); }
        
        COMMAND_data _锁定屏幕方向 = new COMMAND_data() { 命令 = "锁定屏幕方向", 描述 = "", 指令 = "--display-orientation", 参数 = 0, 启用 = false };
        public COMMAND_data 锁定屏幕方向 { get => _锁定屏幕方向; set => Set(ref _锁定屏幕方向, value); }
        
        COMMAND_data _缓冲区 = new COMMAND_data() { 命令 = "缓冲区", 描述 = "", 指令 = "--video-buffer", 参数 = "0", 启用 = true };
        public COMMAND_data 缓冲区 { get => _缓冲区; set => Set(ref _缓冲区, value); }
        
        COMMAND_data _保持常亮 = new COMMAND_data() { 命令 = "保持常亮", 描述 = "", 指令 = "--stay-awake", 参数 = "", 启用 = false };
        public COMMAND_data 保持常亮 { get => _保持常亮; set => Set(ref _保持常亮, value); }
        
        COMMAND_data _ExePath = new COMMAND_data() { 命令 = "ExePath", 描述 = "", 指令 = @"", 参数 = @"D:\sof\scrcpy-win64-v1.17\scrcpy.exe", 启用 = false };
        public COMMAND_data ExePath { get => _ExePath; set => Set(ref _ExePath, value); }

        COMMAND_data _编码器 = new COMMAND_data() { 命令 = "编码器", 描述 = "选择视频编解码器可能的值为：h264（默认值） h265 av1", 指令 = "--video-codec", 参数 = "h264", 启用 = true };
        public COMMAND_data 编码器 { get => _编码器; set => Set(ref _编码器, value); }

        COMMAND_data _UHID鼠标 = new COMMAND_data() { 命令 = "UHID鼠标", 描述 = "", 指令 = "--mouse=uhid", 参数 = "", 启用 = false };
        public COMMAND_data UHID鼠标 { get => _UHID鼠标; set => Set(ref _UHID鼠标, value); }

        COMMAND_data _UHID键盘 = new COMMAND_data() { 命令 = "UHID键盘", 描述 = "", 指令 = "--keyboard=uhid", 参数 = "", 启用 = false };
        public COMMAND_data UHID键盘 { get => _UHID键盘; set => Set(ref _UHID键盘, value); }

        COMMAND_data _无边框 = new COMMAND_data() { 命令 = "无边框", 描述 = "", 指令 = "--window-borderless", 参数 = "", 启用 = false };
        public COMMAND_data 无边框 { get => _无边框; set => Set(ref _无边框, value); }

        // 虚拟显示相关参数
        COMMAND_data _新建虚拟显示 = new COMMAND_data() { 命令 = "新建虚拟显示", 描述 = "创建新的虚拟显示，格式：WIDTHxHEIGHT[/DPI]或空值使用主显示", 指令 = "--new-display", 参数 = "", 启用 = false };
        public COMMAND_data 新建虚拟显示 { get => _新建虚拟显示; set => Set(ref _新建虚拟显示, value); }

        COMMAND_data _启动应用 = new COMMAND_data() { 命令 = "启动应用", 描述 = "在虚拟显示中启动指定应用程序包", 指令 = "--start-app", 参数 = "", 启用 = false };
        public COMMAND_data 启动应用 { get => _启动应用; set => Set(ref _启动应用, value); }

        COMMAND_data _禁用系统装饰 = new COMMAND_data() { 命令 = "禁用系统装饰", 描述 = "禁用虚拟显示中的状态栏和导航栏", 指令 = "--no-vd-system-decorations", 参数 = "", 启用 = false };
        public COMMAND_data 禁用系统装饰 { get => _禁用系统装饰; set => Set(ref _禁用系统装饰, value); }

        COMMAND_data _保留虚拟显示内容 = new COMMAND_data() { 命令 = "保留虚拟显示内容", 描述 = "关闭虚拟显示时将应用移至主显示", 指令 = "--no-vd-destroy-content", 参数 = "", 启用 = false };
        public COMMAND_data 保留虚拟显示内容 { get => _保留虚拟显示内容; set => Set(ref _保留虚拟显示内容, value); }        // 新增属性
        private string _connectionType = "usb";
        public string ConnectionType 
        { 
            get => _connectionType; 
            set 
            {
                Set(ref _connectionType, value);
                IsWifiConnection = value == "wifi" || value == "tcpip";
            }
        }

        private string _ipAddress = "";
        public string IpAddress { get => _ipAddress; set => Set(ref _ipAddress, value); }

        private string _port = "5555";
        public string Port { get => _port; set => Set(ref _port, value); }

        private bool _isWifiConnection = false;
        public bool IsWifiConnection { get => _isWifiConnection; set => Set(ref _isWifiConnection, value); }

        private bool _启用控制 = true;
        public bool 启用控制 { get => _启用控制; set => Set(ref _启用控制, value); }

        private bool _启用录制 = false;
        public bool 启用录制 { get => _启用录制; set => Set(ref _启用录制, value); }

        private string _录制路径 = "";
        public string 录制路径 { get => _录制路径; set => Set(ref _录制路径, value); }        private string _录制格式 = "mp4";
        public string 录制格式 { get => _录制格式; set => Set(ref _录制格式, value); }        private bool _启用音频 = true;
        public bool 启用音频 { get => _启用音频; set => Set(ref _启用音频, value); }

        COMMAND_data _音频码率 = new COMMAND_data() { 命令 = "音频码率", 描述 = "设置音频比特率", 指令 = "--audio-bit-rate", 参数 = "128K", 启用 = true };
        public COMMAND_data 音频码率 { get => _音频码率; set => Set(ref _音频码率, value); }        private string _statusMessage = "就绪";
        public string StatusMessage { get => _statusMessage; set => Set(ref _statusMessage, value); }

        private bool _显示详细日志 = false;
        public bool 显示详细日志 { get => _显示详细日志; set => Set(ref _显示详细日志, value); }

        private bool _启动时检查更新 = true;
        public bool 启动时检查更新 { get => _启动时检查更新; set => Set(ref _启动时检查更新, value); }private int _deviceCount = 0;
        public int DeviceCount { get => _deviceCount; set => Set(ref _deviceCount, value); }

        // 新增的快捷设置属性
        public COMMAND_data 全屏 = new COMMAND_data() { 命令 = "全屏", 描述 = "", 指令 = "--fullscreen", 参数 = "", 启用 = false };
        public COMMAND_data 窗口置顶 = new COMMAND_data() { 命令 = "窗口置顶", 描述 = "", 指令 = "--always-on-top", 参数 = "", 启用 = false };
        public COMMAND_data 关闭设备屏幕 = new COMMAND_data() { 命令 = "关闭设备屏幕", 描述 = "", 指令 = "--turn-screen-off", 参数 = "", 启用 = false };
        public COMMAND_data 显示触摸 = new COMMAND_data() { 命令 = "显示触摸", 描述 = "", 指令 = "--show-touches", 参数 = "", 启用 = false };

        List<string> _Devices = new List<string>();
        public List<string> Devices { get => _Devices; set => Set(ref _Devices, value); }

        // 应用列表相关属性
        List<AppInfo> _InstalledApps = new List<AppInfo>();
        public List<AppInfo> InstalledApps { get => _InstalledApps; set => Set(ref _InstalledApps, value); }

        private AppInfo _selectedApp;
        public AppInfo SelectedApp 
        { 
            get => _selectedApp; 
            set 
            { 
                Set(ref _selectedApp, value);
                if (value != null)
                {
                    启动应用.参数 = value.PackageName;
                }
            } 
        }

        private bool _isLoadingApps = false;
        public bool IsLoadingApps { get => _isLoadingApps; set => Set(ref _isLoadingApps, value); }

        // 应用列表缓存
        private Dictionary<string, List<AppInfo>> _appListCache = new Dictionary<string, List<AppInfo>>();
        private DateTime _lastAppListUpdate = DateTime.MinValue;

        // 设备分辨率列表
        List<string> _deviceResolutions = new List<string>();
        public List<string> DeviceResolutions { get => _deviceResolutions; set => Set(ref _deviceResolutions, value); }        string config_file = "config.json";

        /// <summary>
        /// Initializes a new instance of the MainViewModel class.
        /// </summary>
        public MainViewModel()
        {
              datas1.AddRange(new[]{
                设备,
                码率,
                帧率,
                分辨率,
                画面裁剪,
                锁定屏幕方向,
                缓冲区,
                保持常亮,
                UHID鼠标,
                UHID键盘,
                无边框,
                编码器,
                ExePath,
                全屏,
                窗口置顶,
                关闭设备屏幕,
                显示触摸,
                音频码率,
                // 虚拟显示参数
                新建虚拟显示,
                启动应用,
                禁用系统装饰,
                保留虚拟显示内容
            });

            InitializeCommands();
            LoadConfiguration();
        }

        private void InitializeCommands()
        {
            _E_Submit = new Lazy<RelayCommand>(() => new RelayCommand(() =>
            {
                try
                {
                    StatusMessage = "正在启动...";
                    List<string> strs1 = new List<string>();

                    // 处理连接方式
                    if (ConnectionType == "wifi" && !string.IsNullOrEmpty(IpAddress))
                    {
                        strs1.Add($"--tcpip={IpAddress}:{Port}");
                    }                    // 处理设备选择
                    if (!string.IsNullOrEmpty(设备.参数))
                    {
                        strs1.Add($"--serial {设备.参数}");
                    }// 处理控制模式
                    if (!启用控制)
                    {
                        strs1.Add("--no-control");
                    }

                    // 处理录制
                    if (启用录制 && !string.IsNullOrEmpty(录制路径))
                    {
                        string recordFile = 录制路径;
                        if (!Path.HasExtension(recordFile))
                        {
                            recordFile += $".{录制格式}";
                        }
                        strs1.Add($"--record \"{recordFile}\"");
                        
                        // 添加录制格式参数
                        if (!string.IsNullOrEmpty(录制格式) && 录制格式 != "mp4")
                        {
                            strs1.Add($"--record-format {录制格式}");                        }
                    }

                    // 处理音频设置
                    if (!启用音频)
                    {
                        strs1.Add("--no-audio");
                    }
                    else
                    {
                        音频码率.启用 = true;
                    }

                    // 虚拟显示参数验证
                    if (新建虚拟显示.启用)
                    {
                        // 验证分辨率格式
                        if (!string.IsNullOrEmpty(新建虚拟显示.参数?.ToString()))
                        {
                            string resolution = 新建虚拟显示.参数.ToString();
                            // 允许"自动（使用主显示）"选项
                            if (resolution != "自动（使用主显示）" && !IsValidResolution(resolution))
                            {
                                StatusMessage = "虚拟显示分辨率格式错误";
                                MessageBox.Show("虚拟显示分辨率格式错误\n\n正确格式：\n- 自动（使用主显示）\n- WIDTHxHEIGHT (如: 1920x1080)\n- WIDTHxHEIGHT/DPI (如: 1920x1080/420)\n- /DPI (如: /240，使用主显示尺寸)", 
                                                "参数错误", MessageBoxButton.OK, MessageBoxImage.Error);
                                return;
                            }
                        }
                        
                        // 如果启动应用但没有指定包名，给出提示
                        if (启动应用.启用 && string.IsNullOrEmpty(启动应用.参数?.ToString()))
                        {
                            StatusMessage = "启用启动应用时必须指定应用包名";
                            MessageBox.Show("请输入要在虚拟显示中启动的应用包名\n\n格式示例：\n- com.android.chrome\n- org.videolan.vlc\n- com.tencent.mm", 
                                            "参数错误", MessageBoxButton.OK, MessageBoxImage.Warning);
                            return;
                        }
                    }

                    foreach (var item in datas1)
                    {
                        if (item.启用)
                        {
                            if (item == 设备 && string.IsNullOrEmpty(item.参数))
                            {
                                continue;
                            }

                            // 特殊处理虚拟显示参数，使用等号而不是空格
                            if (item == 新建虚拟显示)
                            {
                                string resolution = item.参数?.ToString() ?? "";
                                // 如果是"自动（使用主显示）"或空值，不指定分辨率参数
                                if (string.IsNullOrEmpty(resolution) || resolution == "自动（使用主显示）")
                                {
                                    strs1.Add(item.指令); // 不指定分辨率，使用主显示的尺寸和密度
                                }
                                else
                                {
                                    strs1.Add($"{item.指令}={resolution}");
                                }
                            }
                            else if (!string.IsNullOrEmpty(item.参数.ToString()))
                            {
                                strs1.Add($"{item.指令} {item.参数}");
                            }
                            else
                            {
                                strs1.Add(item.指令);
                            }
                        }
                    }                    // 检查scrcpy路径
                    if (string.IsNullOrEmpty(ExePath.参数) || !File.Exists(ExePath.参数))
                    {
                        StatusMessage = "请先设置scrcpy.exe路径";
                        MessageBox.Show("请先设置正确的scrcpy.exe路径", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                        return;
                    }

                    string scrcpyPath = ExePath.参数;
                    string workingDir = Path.GetDirectoryName(scrcpyPath);
                    string arguments = string.Join(" ", strs1);
                    
                    MyLog.MyLog.logclass.info($"执行命令: {scrcpyPath} {arguments}");
                    MyLog.MyLog.logclass.info($"工作目录: {workingDir}");
                      // 启动scrcpy进程
                    ProcessStartInfo startInfo = new ProcessStartInfo()
                    {
                        FileName = scrcpyPath,
                        Arguments = arguments,
                        UseShellExecute = false,
                        RedirectStandardOutput = true,
                        RedirectStandardError = true,
                        CreateNoWindow = true, // 隐藏命令行窗口
                        WindowStyle = ProcessWindowStyle.Hidden, // 确保窗口隐藏
                        WorkingDirectory = workingDir
                    };
                      Process scrcpyProcess = new Process();
                    scrcpyProcess.StartInfo = startInfo;                    scrcpyProcess.OutputDataReceived += (s, e) => 
                    {
                        if (!string.IsNullOrEmpty(e.Data))
                        {
                            MyLog.MyLog.logclass.info($"SCRCPY输出: {e.Data}");
                            // 如果用户选择显示详细日志，或者输出包含错误信息，在状态栏显示
                            if (显示详细日志 || e.Data.ToLower().Contains("error") || e.Data.ToLower().Contains("failed"))
                            {
                                Application.Current.Dispatcher.Invoke(() => 
                                {
                                    StatusMessage = e.Data.Contains("error") || e.Data.Contains("failed") 
                                        ? $"SCRCPY警告: {e.Data}" 
                                        : $"SCRCPY: {e.Data}";
                                });
                            }
                        }
                    };
                    scrcpyProcess.ErrorDataReceived += (s, e) => 
                    {
                        if (!string.IsNullOrEmpty(e.Data))
                        {
                            MyLog.MyLog.logclass.error($"SCRCPY错误: {e.Data}");
                            // 错误信息总是显示在状态栏
                            Application.Current.Dispatcher.Invoke(() => 
                            {
                                StatusMessage = $"SCRCPY错误: {e.Data}";
                            });
                        }
                    };
                    
                    // 监控进程退出
                    scrcpyProcess.EnableRaisingEvents = true;
                    scrcpyProcess.Exited += (s, e) => 
                    {
                        Application.Current.Dispatcher.Invoke(() => 
                        {
                            StatusMessage = "SCRCPY已退出";
                            MyLog.MyLog.logclass.info($"SCRCPY进程已退出，退出码: {scrcpyProcess.ExitCode}");
                        });
                    };
                    
                    try
                    {
                        scrcpyProcess.Start();
                        scrcpyProcess.BeginOutputReadLine();
                        scrcpyProcess.BeginErrorReadLine();
                        
                        StatusMessage = "scrcpy已启动";
                        SaveConfiguration();
                    }
                    catch (Exception startEx)
                    {
                        throw new Exception($"启动scrcpy失败: {startEx.Message}");
                    }
                }
                catch (Exception ex)
                {
                    StatusMessage = "启动失败: " + ex.Message;
                    MessageBox.Show($"启动失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            })).Value;            _getDevices = new RelayCommand(() =>
            {
                try
                {
                    StatusMessage = "正在扫描设备...";
                    var deviceList = new List<string>();
                    
                    // 首先尝试从scrcpy目录查找adb
                    string adbPath = "adb";
                    if (!string.IsNullOrEmpty(ExePath.参数) && File.Exists(ExePath.参数))
                    {
                        string scrcpyDir = Path.GetDirectoryName(ExePath.参数);
                        string localAdb = Path.Combine(scrcpyDir, "adb.exe");
                        if (File.Exists(localAdb))
                        {
                            adbPath = localAdb;
                            MyLog.MyLog.logclass.info($"使用本地ADB: {adbPath}");
                        }
                    }
                    else
                    {
                        // 如果没有设置scrcpy路径，提示用户
                        StatusMessage = "建议先设置scrcpy.exe路径以获得更好的兼容性";
                        MyLog.MyLog.logclass.info("使用系统PATH中的ADB");
                    }
                    
                    // 同步执行adb devices命令
                    ProcessStartInfo startInfo = new ProcessStartInfo()
                    {
                        FileName = adbPath,
                        Arguments = "devices",
                        UseShellExecute = false,
                        RedirectStandardOutput = true,
                        RedirectStandardError = true,
                        CreateNoWindow = true
                    };
                    
                    using (Process process = new Process())
                    {
                        process.StartInfo = startInfo;
                        process.Start();
                        
                        string output = process.StandardOutput.ReadToEnd();
                        string error = process.StandardError.ReadToEnd();
                        
                        process.WaitForExit(10000); // 等待最多10秒
                        
                        if (process.ExitCode == 0)
                        {
                            MyLog.MyLog.logclass.info($"ADB输出: {output}");
                            
                            // 解析输出
                            string[] lines = output.Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
                            foreach (string line in lines)
                            {
                                // 跳过标题行"List of devices attached"
                                if (line.Contains("List of devices attached"))
                                    continue;
                                    
                                // 查找设备行，格式为: "设备序列号    device"
                                string trimmedLine = line.Trim();
                                if (trimmedLine.EndsWith("device") && !trimmedLine.EndsWith("unauthorized"))
                                {
                                    // 分割并取第一部分作为设备ID
                                    string[] parts = trimmedLine.Split(new[] { '\t', ' ' }, StringSplitOptions.RemoveEmptyEntries);
                                    if (parts.Length >= 2 && parts[1] == "device")
                                    {
                                        string deviceId = parts[0];
                                        if (!string.IsNullOrEmpty(deviceId))
                                        {
                                            deviceList.Add(deviceId);
                                            MyLog.MyLog.logclass.info($"找到设备: {deviceId}");
                                        }
                                    }
                                }
                            }
                            
                            Devices = deviceList;
                            DeviceCount = deviceList.Count;
                            
                            if (deviceList.Count > 0)
                            {
                                StatusMessage = $"发现 {deviceList.Count} 个设备";
                                // 如果只有一个设备，自动选择它
                                if (deviceList.Count == 1 && string.IsNullOrEmpty(设备.参数))
                                {
                                    设备.参数 = deviceList[0];
                                    MyLog.MyLog.logclass.info($"自动选择设备: {deviceList[0]}");
                                }
                            }
                            else
                            {
                                StatusMessage = "未发现设备，请检查USB调试是否开启";
                                MessageBox.Show("未发现已连接的设备\n\n请确保:\n1. 设备已通过USB连接\n2. 已开启开发者选项\n3. 已开启USB调试\n4. 已授权电脑调试", 
                                                "未发现设备", MessageBoxButton.OK, MessageBoxImage.Information);
                            }
                        }
                        else
                        {
                            MyLog.MyLog.logclass.error($"ADB执行失败，退出码: {process.ExitCode}");
                            MyLog.MyLog.logclass.error($"ADB错误输出: {error}");
                            StatusMessage = "ADB执行失败，请检查ADB是否安装";
                            MessageBox.Show($"ADB执行失败\n\n错误信息: {error}\n\n请确保:\n1. 已安装ADB工具或使用scrcpy自带的ADB\n2. ADB在系统PATH中或设置了正确的scrcpy路径\n3. USB驱动已正确安装", 
                                            "ADB错误", MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    }
                }
                catch (Exception ex)
                {
                    StatusMessage = "扫描设备失败";
                    MyLog.MyLog.logclass.error($"扫描设备异常: {ex.Message}");
                    MessageBox.Show($"扫描设备失败: {ex.Message}\n\n请确保:\n1. 已安装ADB工具\n2. 系统PATH中包含ADB路径\n3. 或设置了正确的scrcpy.exe路径", 
                                    "扫描设备异常", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            });

            BrowseExePathCommand = new RelayCommand(() =>
            {
                var dialog = new OpenFileDialog()
                {
                    Title = "选择 scrcpy.exe 文件",
                    Filter = "可执行文件 (*.exe)|*.exe|所有文件 (*.*)|*.*",
                    CheckFileExists = true
                };

                if (dialog.ShowDialog() == true)
                {
                    ExePath.参数 = dialog.FileName;
                }
            });

            BrowseRecordPathCommand = new RelayCommand(() =>
            {
                var dialog = new SaveFileDialog()
                {
                    Title = "选择录制文件保存位置",
                    Filter = "MP4 文件 (*.mp4)|*.mp4|MKV 文件 (*.mkv)|*.mkv|所有文件 (*.*)|*.*",
                    DefaultExt = 录制格式
                };

                if (dialog.ShowDialog() == true)
                {
                    录制路径 = dialog.FileName;
                }            });

            ShowHelpCommand = new RelayCommand(() =>
            {
                var helpText = "Scrcpy 使用说明：\n\n" +
                    "1. 设备连接：\n" +
                    "   - USB连接：直接连接设备，启用USB调试\n" +
                    "   - WiFi连接：设备与电脑在同一网络，输入设备IP地址\n\n" +
                    "2. 常用快捷键：\n" +
                    "   - Ctrl+F: 全屏\n" +
                    "   - Ctrl+G: 调整窗口大小\n" +
                    "   - Ctrl+H: 返回键\n" +
                    "   - Ctrl+S: 切换应用\n" +
                    "   - Ctrl+M: 菜单键\n" +
                    "   - Ctrl+P: 电源键\n\n" +
                    "3. 录制功能：\n" +
                    "   - 勾选启用录制，选择保存路径\n" +
                    "   - 支持 MP4、MKV 等格式\n\n" +
                    "4. 高级设置：\n" +
                    "   - 音频设置、相机控制、网络配置等\n" +
                    "   - 点击'高级设置'按钮进行配置\n\n" +
                    "更多信息请访问：https://github.com/Genymobile/scrcpy";                MessageBox.Show(helpText, "帮助", MessageBoxButton.OK, MessageBoxImage.Information);
            });            ShowAdvancedSettingsCommand = new RelayCommand(() =>
            {
                try
                {
                    // 直接创建高级设置窗口
                    var advancedWindow = new Views.AdvancedSettingsWindow();
                    advancedWindow.Owner = Application.Current.MainWindow;
                    
                    // 显示窗口并获取结果
                    bool? result = advancedWindow.ShowDialog();
                    
                    if (result == true)
                    {
                        // 用户点击了确定按钮，可以在这里处理高级设置的结果
                        StatusMessage = "高级设置已更新";
                        MyLog.MyLog.logclass.info("用户更新了高级设置");
                    }
                }
                catch (Exception ex)
                {
                    MyLog.MyLog.logclass.error($"打开高级设置失败: {ex.Message}");
                    MessageBox.Show($"打开高级设置失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            });

            GetInstalledAppsCommand = new RelayCommand(async () =>
            {
                await GetInstalledAppsAsync();
            });

            GetDeviceResolutionsCommand = new RelayCommand(async () =>
            {
                await GetDeviceResolutionsAsync();
            });}

        private void LoadConfiguration()
        {
            if (File.Exists(config_file))
            {
                try
                {
                    var a001 = 序列化.序列化.json文件反序列化<List<COMMAND_data>>(config_file);
                    var config1 = new TypeAdapterConfig() { };
                    config1.ForType<COMMAND_data, COMMAND_data>().Ignore(s => s.指令, s => s.描述);
                    datas1.ForEach(s =>
                    {
                        a001.Find(s1 => s1.命令 == s.命令)?.Adapt(s, config1);
                    });
                }                catch (Exception)
                {
                    StatusMessage = "配置加载失败";
                }
            }
            datas1.Find(s => s.命令 == "ExePath").启用 = false;
        }

        private void SaveConfiguration()
        {
            try
            {
                序列化.序列化.序列化为json文件(config_file, datas1);
            }
            catch (Exception ex)
            {
                MyLog.MyLog.logclass.error($"保存配置失败: {ex.Message}");
            }
        }

        // Commands
        RelayCommand _E_Submit = null;
        public RelayCommand E_Submit { get => _E_Submit; set => Set(ref _E_Submit, value); }
        
        RelayCommand _getDevices = null;
        public RelayCommand getDevices { get => _getDevices; set => Set(ref _getDevices, value); }        public RelayCommand BrowseExePathCommand { get; set; }
        public RelayCommand BrowseRecordPathCommand { get; set; }
        public RelayCommand ShowHelpCommand { get; set; }
        public RelayCommand ShowAdvancedSettingsCommand { get; set; }
        public RelayCommand GetInstalledAppsCommand { get; set; }
        public RelayCommand GetDeviceResolutionsCommand { get; set; }

        /// <summary>
        /// 异步获取设备上已安装的应用程序列表
        /// </summary>
        private async Task GetInstalledAppsAsync()
        {
            try
            {
                IsLoadingApps = true;
                StatusMessage = "正在获取应用列表...";
                
                // 检查是否有选中的设备
                if (string.IsNullOrEmpty(设备.参数))
                {
                    StatusMessage = "请先选择设备";
                    MessageBox.Show("请先选择要获取应用列表的设备", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                // 检查缓存，如果5分钟内获取过相同设备的应用列表，直接使用缓存
                string cacheKey = 设备.参数;
                if (_appListCache.ContainsKey(cacheKey) && 
                    DateTime.Now - _lastAppListUpdate < TimeSpan.FromMinutes(5))
                {
                    InstalledApps = _appListCache[cacheKey];
                    StatusMessage = $"从缓存加载 {InstalledApps.Count} 个应用";
                    return;
                }

                var appList = new List<AppInfo>();
                
                // 构建adb路径
                string adbPath = "adb";
                if (!string.IsNullOrEmpty(ExePath.参数) && File.Exists(ExePath.参数))
                {
                    string scrcpyDir = Path.GetDirectoryName(ExePath.参数);
                    string localAdb = Path.Combine(scrcpyDir, "adb.exe");
                    if (File.Exists(localAdb))
                    {
                        adbPath = localAdb;
                    }
                }

                // 获取已安装的应用包列表（所有应用包）
                await Task.Run(() =>
                {
                    // 获取所有已安装的应用包，不限制类型
                    var allInstalledPackages = GetAllInstalledPackages(adbPath, 设备.参数);
                    MyLog.MyLog.logclass.info($"获取到 {allInstalledPackages.Count} 个已安装应用包");
                    
                    // 获取有启动器图标的应用列表，用于判断是否为用户应用
                    var launcherApps = GetLauncherApps(adbPath, 设备.参数);
                    
                    // 过滤掉一些明显不需要的系统包
                    var filteredPackages = FilterUsefulPackages(allInstalledPackages, launcherApps);
                    MyLog.MyLog.logclass.info($"过滤后剩余 {filteredPackages.Count} 个有用应用包");
                    
                    // 智能处理大量应用包
                    int maxCount = filteredPackages.Count;
                    bool useSimpleMode = false;
                    
                    if (maxCount > 300)
                    {
                        MyLog.MyLog.logclass.info($"检测到 {maxCount} 个应用包，为了性能将使用简化模式处理前300个");
                        maxCount = 300;
                        useSimpleMode = true;
                    }
                    else if (maxCount > 200)
                    {
                        MyLog.MyLog.logclass.info($"检测到 {maxCount} 个应用包，将简化部分应用详细信息获取以提高性能");
                        useSimpleMode = true;
                    }
                    
                    for (int i = 0; i < maxCount; i++)
                    {
                        string packageName = filteredPackages[i];
                        try
                        {
                            AppInfo appInfo;
                            
                            if (useSimpleMode && i > 150)
                            {
                                // 简化模式：对于大量应用，直接使用基本信息，避免太多ADB调用
                                appInfo = new AppInfo
                                {
                                    PackageName = packageName,
                                    Label = GetFriendlyAppName(packageName),
                                    DisplayName = GetFriendlyAppName(packageName),
                                    IsSystemApp = launcherApps.IndexOf(packageName) < 0
                                };
                            }
                            else
                            {
                                // 正常模式：获取详细信息
                                appInfo = GetDetailedAppInfo(adbPath, 设备.参数, packageName);
                                if (appInfo != null)
                                {
                                    // 标记是否为有启动器的应用
                                    appInfo.IsSystemApp = launcherApps.IndexOf(packageName) < 0;
                                }
                            }
                            
                            if (appInfo != null)
                            {
                                appList.Add(appInfo);
                            }
                        }
                        catch (Exception ex)
                        {
                            MyLog.MyLog.logclass.error($"获取应用 {packageName} 详细信息失败: {ex.Message}");
                            // 如果获取详细信息失败，至少保留基本信息
                            appList.Add(new AppInfo
                            {
                                PackageName = packageName,
                                Label = GetFriendlyAppName(packageName),
                                DisplayName = GetFriendlyAppName(packageName),
                                IsSystemApp = launcherApps.IndexOf(packageName) < 0
                            });
                        }
                    }
                });

                // 按应用名称排序
                appList.Sort((app1, app2) => string.Compare(app1.Label, app2.Label, StringComparison.OrdinalIgnoreCase));
                
                // 添加一些常用的系统应用
                appList.Insert(0, new AppInfo { PackageName = "com.android.settings", Label = "设置", DisplayName = "设置", IsSystemApp = true });
                appList.Insert(0, new AppInfo { PackageName = "com.android.chrome", Label = "Chrome浏览器", DisplayName = "Chrome浏览器", IsSystemApp = false });
                
                // 保存到缓存
                _appListCache[cacheKey] = appList;
                _lastAppListUpdate = DateTime.Now;
                
                InstalledApps = appList;
                StatusMessage = $"获取到 {appList.Count} 个应用";
                MyLog.MyLog.logclass.info($"成功获取 {appList.Count} 个应用");
            }
            catch (Exception ex)
            {
                StatusMessage = "获取应用列表失败";
                MyLog.MyLog.logclass.error($"获取应用列表异常: {ex.Message}");
                MessageBox.Show($"获取应用列表失败: {ex.Message}\n\n请确保:\n1. 设备已连接并授权\n2. ADB工具可用\n3. 设备USB调试已开启", 
                                "获取应用列表失败", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                IsLoadingApps = false;
            }
        }

        /// <summary>
        /// 异步获取设备分辨率信息
        /// </summary>
        private async Task GetDeviceResolutionsAsync()
        {
            try
            {
                StatusMessage = "正在获取设备分辨率...";
                
                // 检查是否有选中的设备
                if (string.IsNullOrEmpty(设备.参数))
                {
                    StatusMessage = "请先选择设备";
                    MessageBox.Show("请先选择要获取分辨率的设备", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                var resolutions = new List<string>();
                
                // 构建adb路径
                string adbPath = "adb";
                if (!string.IsNullOrEmpty(ExePath.参数) && File.Exists(ExePath.参数))
                {
                    string scrcpyDir = Path.GetDirectoryName(ExePath.参数);
                    string localAdb = Path.Combine(scrcpyDir, "adb.exe");
                    if (File.Exists(localAdb))
                    {
                        adbPath = localAdb;
                    }
                }

                await Task.Run(() =>
                {
                    // 获取设备的物理尺寸和密度
                    var deviceInfo = GetDeviceDisplayInfo(adbPath, 设备.参数);
                    
                    // 添加基础分辨率选项
                    resolutions.Add("自动（使用主显示）");
                    
                    if (deviceInfo.IsValid)
                    {
                        // 原生分辨率
                        resolutions.Add($"{deviceInfo.Width}x{deviceInfo.Height}");
                        if (deviceInfo.Density > 0)
                        {
                            resolutions.Add($"{deviceInfo.Width}x{deviceInfo.Height}/{deviceInfo.Density}");
                        }
                        
                        // 横屏分辨率
                        if (deviceInfo.Width < deviceInfo.Height)
                        {
                            resolutions.Add($"{deviceInfo.Height}x{deviceInfo.Width}");
                        }
                        
                        // 生成常用比例的分辨率
                        GenerateCommonResolutions(resolutions, deviceInfo.Width, deviceInfo.Height, deviceInfo.Density);
                    }
                    
                    // 添加常用预设分辨率
                    AddCommonPresetResolutions(resolutions);
                });

                // 去除重复的分辨率选项
                var uniqueResolutions = new List<string>();
                foreach (var resolution in resolutions)
                {
                    if (!uniqueResolutions.Contains(resolution))
                    {
                        uniqueResolutions.Add(resolution);
                    }
                }
                DeviceResolutions = uniqueResolutions;
                StatusMessage = $"获取到 {DeviceResolutions.Count} 个分辨率选项";
                MyLog.MyLog.logclass.info($"成功获取设备分辨率，共 {DeviceResolutions.Count} 个选项");
            }
            catch (Exception ex)
            {
                StatusMessage = "获取设备分辨率失败";
                MyLog.MyLog.logclass.error($"获取设备分辨率异常: {ex.Message}");
                MessageBox.Show($"获取设备分辨率失败: {ex.Message}\n\n将使用预设分辨率列表", 
                                "获取分辨率失败", MessageBoxButton.OK, MessageBoxImage.Warning);
                
                // 使用预设分辨率
                var fallbackResolutions = new List<string>();
                AddCommonPresetResolutions(fallbackResolutions);
                DeviceResolutions = fallbackResolutions;
            }
        }

        /// <summary>
        /// 获取设备显示信息
        /// </summary>
        private DeviceDisplayInfo GetDeviceDisplayInfo(string adbPath, string deviceSerial)
        {
            try
            {
                // 获取屏幕分辨率
                var sizeInfo = ExecuteAdbCommand(adbPath, deviceSerial, "shell wm size");
                var densityInfo = ExecuteAdbCommand(adbPath, deviceSerial, "shell wm density");
                
                int width = 0, height = 0, density = 0;
                
                // 解析分辨率 "Physical size: 1080x2340"
                if (!string.IsNullOrEmpty(sizeInfo))
                {
                    var sizeMatch = Regex.Match(sizeInfo, @"(\d+)x(\d+)");
                    if (sizeMatch.Success)
                    {
                        int.TryParse(sizeMatch.Groups[1].Value, out width);
                        int.TryParse(sizeMatch.Groups[2].Value, out height);
                    }
                }
                
                // 解析密度 "Physical density: 420"
                if (!string.IsNullOrEmpty(densityInfo))
                {
                    var densityMatch = Regex.Match(densityInfo, @"(\d+)");
                    if (densityMatch.Success)
                    {
                        int.TryParse(densityMatch.Groups[1].Value, out density);
                    }
                }
                
                return new DeviceDisplayInfo(width, height, density);
            }
            catch
            {
                return new DeviceDisplayInfo(0, 0, 0);
            }
        }

        /// <summary>
        /// 执行ADB命令并返回输出
        /// </summary>
        private string ExecuteAdbCommand(string adbPath, string deviceSerial, string command)
        {
            try
            {
                ProcessStartInfo startInfo = new ProcessStartInfo()
                {
                    FileName = adbPath,
                    Arguments = $"-s {deviceSerial} {command}",
                    UseShellExecute = false,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    CreateNoWindow = true
                };

                using (Process process = new Process())
                {
                    process.StartInfo = startInfo;
                    process.Start();
                    
                    string output = process.StandardOutput.ReadToEnd();
                    process.WaitForExit(5000);
                    
                    return process.ExitCode == 0 ? output : string.Empty;
                }
            }
            catch
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// 生成常用比例的分辨率
        /// </summary>
        private void GenerateCommonResolutions(List<string> resolutions, int deviceWidth, int deviceHeight, int deviceDensity)
        {
            var commonSizes = new[] { 720, 1080, 1440, 1600, 2160 };
            
            foreach (var size in commonSizes)
            {
                if (size != Math.Max(deviceWidth, deviceHeight))
                {
                    // 保持宽高比
                    double aspectRatio = (double)deviceWidth / deviceHeight;
                    
                    if (deviceWidth > deviceHeight) // 横屏设备
                    {
                        int newWidth = size;
                        int newHeight = (int)(size / aspectRatio);
                        resolutions.Add($"{newWidth}x{newHeight}");
                    }
                    else // 竖屏设备
                    {
                        int newHeight = size;
                        int newWidth = (int)(size * aspectRatio);
                        resolutions.Add($"{newWidth}x{newHeight}");
                    }
                }
            }
            
            // 添加DPI变体
            if (deviceDensity > 0)
            {
                var commonDensities = new[] { 240, 320, 420, 480, 640 };
                foreach (var dpi in commonDensities)
                {
                    if (dpi != deviceDensity)
                    {
                        resolutions.Add($"/{dpi}");
                    }
                }
            }
        }

        /// <summary>
        /// 添加常用预设分辨率
        /// </summary>
        private void AddCommonPresetResolutions(List<string> resolutions)
        {
            resolutions.Add("自动（使用主显示）");
            
            // 常用手机分辨率
            resolutions.AddRange(new[]
            {
                "720x1280",    // HD
                "750x1334",    // iPhone 6/7/8
                "1080x1920",   // Full HD
                "1080x2340",   // 现代手机常用
                "1125x2436",   // iPhone X系列
                "1170x2532",   // iPhone 12/13 Pro
                "1284x2778",   // iPhone 12/13 Pro Max
                "1440x2560",   // 2K
                "1440x3040",   // Galaxy S8+
                "1440x3200",   // Galaxy S20
                "1600x2560",   // 平板常用
                "2160x3840",   // 4K
            });
            
            // 常用平板分辨率
            resolutions.AddRange(new[]
            {
                "1024x768",    // iPad 经典
                "2048x1536",   // iPad Air
                "2224x1668",   // iPad Pro 10.5
                "2388x1668",   // iPad Pro 11
                "2732x2048",   // iPad Pro 12.9
                "1920x1080",   // 横屏Full HD
                "2560x1440",   // 横屏2K
            });
            
            // DPI选项
            resolutions.AddRange(new[]
            {
                "/160",  // mdpi
                "/240",  // hdpi
                "/320",  // xhdpi
                "/420",  // xxhdpi
                "/480",  // xxxhdpi
                "/640"   // ultra high dpi
            });
        }

        /// <summary>
        /// 获取包列表
        /// </summary>
        private List<string> GetPackageList(string adbPath, string deviceSerial, string flags = "")
        {
            var packages = new List<string>();
            try
            {
                string output = ExecuteAdbCommand(adbPath, deviceSerial, $"shell pm list packages {flags}");
                if (!string.IsNullOrEmpty(output))
                {
                    string[] lines = output.Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string line in lines)
                    {
                        if (line.StartsWith("package:"))
                        {
                            string packageName = line.Substring("package:".Length).Trim();
                            if (!string.IsNullOrEmpty(packageName))
                            {
                                packages.Add(packageName);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MyLog.MyLog.logclass.error($"获取包列表失败: {ex.Message}");
            }
            return packages;
        }

        /// <summary>
        /// 获取所有已安装的应用包
        /// </summary>
        private List<string> GetAllInstalledPackages(string adbPath, string deviceSerial)
        {
            var packages = new List<string>();
            try
            {
                // 使用不带任何标志的 pm list packages 获取所有应用包
                string output = ExecuteAdbCommand(adbPath, deviceSerial, "shell pm list packages");
                if (!string.IsNullOrEmpty(output))
                {
                    string[] lines = output.Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string line in lines)
                    {
                        if (line.StartsWith("package:"))
                        {
                            string packageName = line.Substring("package:".Length).Trim();
                            if (!string.IsNullOrEmpty(packageName))
                            {
                                packages.Add(packageName);
                            }
                        }
                    }
                }
                MyLog.MyLog.logclass.info($"pm list packages 返回 {packages.Count} 个应用包");
            }
            catch (Exception ex)
            {
                MyLog.MyLog.logclass.error($"获取所有应用包失败: {ex.Message}");
                // 如果失败，回退到原来的方法
                var thirdPartyApps = GetPackageList(adbPath, deviceSerial, "-3");
                var systemApps = GetLauncherApps(adbPath, deviceSerial);
                packages.AddRange(thirdPartyApps);
                foreach (var systemApp in systemApps)
                {
                    if (!packages.Contains(systemApp))
                    {
                        packages.Add(systemApp);
                    }
                }
            }
            return packages;
        }

        /// <summary>
        /// 过滤出有用的应用包，排除一些明显不需要的系统服务包
        /// </summary>
        private List<string> FilterUsefulPackages(List<string> allPackages, List<string> launcherApps)
        {
            var filteredPackages = new List<string>();
            
            // 只排除明显不需要的系统服务包（大幅减少排除项）
            var excludePatterns = new[]
            {
                "com.android.internal.",      // 内部服务
                "com.android.providers.",     // 数据提供者
                "com.android.shell",          // Shell服务
                "com.android.keychain",       // 密钥链
                "com.android.backupconfirm",  // 备份确认
                "com.android.cts.",           // CTS测试
                "com.android.defcontainer",   // 默认容器
                "com.android.externalstorage", // 外部存储
                "com.google.android.partnersetup", // 合作伙伴设置
                "com.google.android.setupwizard",  // 设置向导
                "com.qualcomm.qti",           // 高通服务
                "com.qti.qualcomm",           // QTI服务
                "android.ext."                // Android扩展服务
            };

            // 第一步：添加所有有启动器图标的应用（这些肯定是用户可见的）
            foreach (var launcherApp in launcherApps)
            {
                if (allPackages.Contains(launcherApp) && !filteredPackages.Contains(launcherApp))
                {
                    filteredPackages.Add(launcherApp);
                }
            }

            // 第二步：添加所有第三方应用和大部分系统应用
            foreach (var package in allPackages)
            {
                if (filteredPackages.Contains(package))
                    continue;

                // 检查是否应该排除（只排除明显的系统服务）
                bool shouldExclude = false;
                foreach (var pattern in excludePatterns)
                {
                    if (package.StartsWith(pattern))
                    {
                        shouldExclude = true;
                        break;
                    }
                }

                // 额外排除一些特殊情况
                if (!shouldExclude)
                {
                    // 排除一些明显的测试包或临时包
                    if (package.Contains(".test.") || 
                        package.Contains(".testing.") ||
                        package.EndsWith(".test") ||
                        package.StartsWith("test.") ||
                        package.Equals("android") ||
                        package.StartsWith("com.android.cts"))
                    {
                        shouldExclude = true;
                    }
                }

                if (!shouldExclude)
                {
                    filteredPackages.Add(package);
                }
            }

            // 确保一些重要的系统应用被包含（即使可能被意外排除）
            var essentialSystemApps = new[]
            {
                "com.android.settings",
                "com.android.camera", "com.android.camera2",
                "com.android.gallery3d", "com.google.android.gallery3d",
                "com.android.calculator2",
                "com.android.contacts",
                "com.android.dialer", "com.google.android.dialer",
                "com.android.mms", "com.google.android.apps.messaging",
                "com.android.email", "com.google.android.gm",
                "com.android.calendar", "com.google.android.calendar",
                "com.android.browser", "com.android.chrome",
                "com.android.documentsui",
                "com.android.clock", "com.android.deskclock",
                "com.android.music", "com.google.android.music",
                "com.android.systemui"  // 也包含系统UI，某些情况下可能需要
            };

            foreach (var essentialApp in essentialSystemApps)
            {
                if (allPackages.Contains(essentialApp) && !filteredPackages.Contains(essentialApp))
                {
                    filteredPackages.Add(essentialApp);
                }
            }

            MyLog.MyLog.logclass.info($"过滤逻辑：原始应用 {allPackages.Count} 个 → 过滤后 {filteredPackages.Count} 个");
            return filteredPackages;
        }

        /// <summary>
        /// 获取启动器应用列表（系统应用中有启动图标的）
        /// </summary>
        private List<string> GetLauncherApps(string adbPath, string deviceSerial)
        {
            var launcherApps = new List<string>();
            try
            {
                // 方法1: 使用 pm query-activities 获取所有启动器应用
                string queryOutput = ExecuteAdbCommand(adbPath, deviceSerial, 
                    "shell pm query-activities -c android.intent.category.LAUNCHER");
                
                if (!string.IsNullOrEmpty(queryOutput))
                {
                    string[] lines = queryOutput.Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string line in lines)
                    {
                        // 解析包名，格式可能是: "Activity: com.example.app/.MainActivity"
                        var match = Regex.Match(line, @"Activity:\s*([^/\s]+)");
                        if (match.Success)
                        {
                            string packageName = match.Groups[1].Value.Trim();
                            if (!string.IsNullOrEmpty(packageName) && !launcherApps.Contains(packageName))
                            {
                                launcherApps.Add(packageName);
                            }
                        }
                    }
                }

                // 方法2: 使用 cmd package query-activities (Android 6.0+)
                if (launcherApps.Count < 5)
                {
                    string cmdOutput = ExecuteAdbCommand(adbPath, deviceSerial, 
                        "shell cmd package query-activities -c android.intent.category.LAUNCHER");
                    
                    if (!string.IsNullOrEmpty(cmdOutput))
                    {
                        string[] lines = cmdOutput.Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
                        foreach (string line in lines)
                        {
                            var packageMatch = Regex.Match(line, @"package:\s*([^\s]+)");
                            if (packageMatch.Success)
                            {
                                string packageName = packageMatch.Groups[1].Value.Trim();
                                if (!string.IsNullOrEmpty(packageName) && !launcherApps.Contains(packageName))
                                {
                                    launcherApps.Add(packageName);
                                }
                            }
                        }
                    }
                }

                // 方法3: 备用方法 - 添加常用的系统应用
                var essentialSystemApps = new[]
                {
                    "com.android.settings",
                    "com.android.camera",
                    "com.android.camera2", 
                    "com.android.gallery3d",
                    "com.google.android.gallery3d",
                    "com.android.calculator2",
                    "com.android.contacts",
                    "com.android.dialer",
                    "com.android.clock",
                    "com.android.deskclock",
                    "com.android.documentsui",
                    "com.android.chrome",
                    "com.google.android.gm",
                    "com.google.android.apps.maps",
                    "com.google.android.youtube"
                };
                
                foreach (var app in essentialSystemApps)
                {
                    if (!launcherApps.Contains(app))
                    {
                        // 验证应用是否真的存在
                        string verifyOutput = ExecuteAdbCommand(adbPath, deviceSerial, $"shell pm list packages {app}");
                        if (!string.IsNullOrEmpty(verifyOutput) && verifyOutput.Contains($"package:{app}"))
                        {
                            launcherApps.Add(app);
                        }
                    }
                }

                MyLog.MyLog.logclass.info($"获取到 {launcherApps.Count} 个启动器应用");
            }
            catch (Exception ex)
            {
                MyLog.MyLog.logclass.error($"获取启动器应用失败: {ex.Message}");
                
                // 最后的备用方案：添加一些基本的系统应用
                var basicApps = new[]
                {
                    "com.android.settings",
                    "com.android.camera",
                    "com.android.calculator2"
                };
                launcherApps.AddRange(basicApps);
            }
            
            return launcherApps;
        }

        /// <summary>
        /// 获取应用详细信息
        /// </summary>
        private AppInfo GetDetailedAppInfo(string adbPath, string deviceSerial, string packageName)
        {
            try
            {
                var appInfo = new AppInfo
                {
                    PackageName = packageName,
                    Label = GetFriendlyAppName(packageName),
                    DisplayName = GetFriendlyAppName(packageName),
                    IsSystemApp = false
                };

                // 尝试多种方法获取应用的实际名称
                string actualLabel = GetActualAppLabel(adbPath, deviceSerial, packageName);
                if (!string.IsNullOrEmpty(actualLabel))
                {
                    appInfo.Label = actualLabel;
                    appInfo.DisplayName = actualLabel;
                }

                return appInfo;
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// 获取应用的真实标签名称
        /// </summary>
        private string GetActualAppLabel(string adbPath, string deviceSerial, string packageName)
        {
            try
            {
                // 优先使用友好名称映射，因为它们是最准确的
                string friendlyName = GetFriendlyAppName(packageName);
                if (!friendlyName.Equals(packageName))
                {
                    return friendlyName;
                }

                // 方法1: 使用 pm path + aapt dump badging (最可靠的方法)
                string apkPath = GetApkPath(adbPath, deviceSerial, packageName);
                if (!string.IsNullOrEmpty(apkPath))
                {
                    string aaptOutput = ExecuteAdbCommand(adbPath, deviceSerial, 
                        $"shell aapt dump badging {apkPath}");
                    
                    if (!string.IsNullOrEmpty(aaptOutput))
                    {
                        // 优先查找中文标签
                        var zhLabelMatch = Regex.Match(aaptOutput, @"application-label-zh[^:]*:'([^']+)'");
                        if (zhLabelMatch.Success)
                        {
                            return zhLabelMatch.Groups[1].Value;
                        }
                        
                        // 然后查找默认标签
                        var labelMatch = Regex.Match(aaptOutput, @"application-label:'([^']+)'");
                        if (labelMatch.Success)
                        {
                            return labelMatch.Groups[1].Value;
                        }
                        
                        // 查找任何本地化标签
                        var anyLocalizedMatch = Regex.Match(aaptOutput, @"application-label-[^:]*:'([^']+)'");
                        if (anyLocalizedMatch.Success)
                        {
                            return anyLocalizedMatch.Groups[1].Value;
                        }
                    }
                }

                // 方法2: 使用 dumpsys package 获取 nonLocalizedLabel
                string dumpsysOutput = ExecuteAdbCommand(adbPath, deviceSerial, 
                    $"shell dumpsys package {packageName}");
                
                if (!string.IsNullOrEmpty(dumpsysOutput))
                {
                    var nonLocalizedMatch = Regex.Match(dumpsysOutput, @"nonLocalizedLabel=([^\s]+)");
                    if (nonLocalizedMatch.Success)
                    {
                        string label = nonLocalizedMatch.Groups[1].Value;
                        if (!label.Equals("null") && label.Length > 1)
                        {
                            return label;
                        }
                    }
                }

                // 方法3: 如果是常见的应用类型，尝试从包名推断名称
                return InferAppNameFromPackage(packageName);
            }
            catch (Exception ex)
            {
                MyLog.MyLog.logclass.error($"获取应用 {packageName} 标签失败: {ex.Message}");
                return InferAppNameFromPackage(packageName);
            }
        }

        /// <summary>
        /// 从包名推断应用名称
        /// </summary>
        private string InferAppNameFromPackage(string packageName)
        {
            if (string.IsNullOrEmpty(packageName))
                return "未知应用";

            // 移除常见的前缀
            string name = packageName;
            var prefixes = new[] { "com.android.", "com.google.android.", "org.", "com.", "cn." };
            foreach (var prefix in prefixes)
            {
                if (name.StartsWith(prefix))
                {
                    name = name.Substring(prefix.Length);
                    break;
                }
            }

            // 使用最后一个部分作为应用名称
            if (name.Contains("."))
            {
                var parts = name.Split('.');
                name = parts[parts.Length - 1];
            }

            // 如果名称太短或是常见的无意义词汇，返回包名
            if (name.Length <= 2 || name.Equals("app") || name.Equals("main") || name.Equals("client"))
            {
                return packageName;
            }

            // 首字母大写
            return char.ToUpper(name[0]) + name.Substring(1).ToLower();
        }

        /// <summary>
        /// 获取应用APK文件路径
        /// </summary>
        private string GetApkPath(string adbPath, string deviceSerial, string packageName)
        {
            try
            {
                string output = ExecuteAdbCommand(adbPath, deviceSerial, 
                    $"shell pm path {packageName}");
                
                if (!string.IsNullOrEmpty(output))
                {
                    var match = Regex.Match(output, @"package:(.+\.apk)");
                    if (match.Success)
                    {
                        return match.Groups[1].Value.Trim();
                    }
                }
                
                return string.Empty;
            }
            catch
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// 获取应用的显示标签
        /// </summary>
        private string GetAppLabel(string adbPath, string deviceSerial, string packageName)
        {
            try
            {
                // 尝试获取应用的显示名称
                ProcessStartInfo startInfo = new ProcessStartInfo()
                {
                    FileName = adbPath,
                    Arguments = $"-s {deviceSerial} shell pm list packages -f {packageName}",
                    UseShellExecute = false,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    CreateNoWindow = true
                };

                using (Process process = new Process())
                {
                    process.StartInfo = startInfo;
                    process.Start();
                    
                    string output = process.StandardOutput.ReadToEnd();
                    process.WaitForExit(3000);
                    
                    if (process.ExitCode == 0 && !string.IsNullOrEmpty(output))
                    {
                        // 如果找到包，尝试获取更友好的名称
                        return GetFriendlyAppName(packageName);
                    }
                }
                
                return packageName;
            }
            catch
            {
                return packageName;
            }
        }

        /// <summary>
        /// 获取友好的应用名称
        /// </summary>
        private string GetFriendlyAppName(string packageName)
        {
            // 常见应用的友好名称映射
            var friendlyNames = new Dictionary<string, string>
            {
                // 系统应用
                { "com.android.settings", "系统设置" },
                { "com.android.camera", "相机" },
                { "com.android.camera2", "相机" },
                { "com.android.gallery3d", "图库" },
                { "com.google.android.gallery3d", "图库" },
                { "com.android.music", "音乐" },
                { "com.android.calculator2", "计算器" },
                { "com.android.contacts", "联系人" },
                { "com.android.dialer", "电话" },
                { "com.android.mms", "短信" },
                { "com.android.email", "邮件" },
                { "com.android.calendar", "日历" },
                { "com.android.browser", "浏览器" },
                { "com.android.documentsui", "文件管理器" },
                { "com.android.fileexplorer", "文件管理器" },
                { "com.android.clock", "时钟" },
                { "com.android.deskclock", "时钟" },
                
                // 浏览器
                { "com.android.chrome", "Chrome浏览器" },
                { "com.google.android.browser", "Google浏览器" },
                { "org.mozilla.firefox", "Firefox浏览器" },
                { "com.opera.browser", "Opera浏览器" },
                { "com.UCMobile", "UC浏览器" },
                { "com.qihoo.browser", "360浏览器" },
                
                // 社交应用
                { "com.tencent.mm", "微信" },
                { "com.tencent.mobileqq", "QQ" },
                { "com.sina.weibo", "微博" },
                { "com.facebook.katana", "Facebook" },
                { "com.twitter.android", "Twitter" },
                { "com.instagram.android", "Instagram" },
                { "com.whatsapp", "WhatsApp" },
                { "com.telegram.messenger", "Telegram" },
                { "com.linkedin.android", "LinkedIn" },
                { "com.discord", "Discord" },
                { "com.snapchat.android", "Snapchat" },
                { "com.zhiliaoapp.musically", "TikTok" },
                { "com.ss.android.ugc.aweme", "抖音" },
                { "com.smile.gifmaker", "快手" },
                
                // 视频娱乐
                { "com.youtube.android", "YouTube" },
                { "com.google.android.youtube", "YouTube" },
                { "com.netflix.mediaclient", "Netflix" },
                { "com.iqiyi.i18n", "爱奇艺" },
                { "com.qiyi.video", "爱奇艺" },
                { "com.youku.phone", "优酷" },
                { "tv.danmaku.bili", "哔哩哔哩" },
                { "com.bilibili.app.in", "哔哩哔哩" },
                { "air.tv.douyu.android", "斗鱼" },
                { "com.tencent.qqlive", "腾讯视频" },
                { "com.baidu.video", "百度视频" },
                { "org.videolan.vlc", "VLC播放器" },
                
                // 音乐应用
                { "com.netease.cloudmusic", "网易云音乐" },
                { "com.kugou.android", "酷狗音乐" },
                { "cn.kuwo.player", "酷我音乐" },
                { "com.tencent.qqmusic", "QQ音乐" },
                { "com.spotify.music", "Spotify" },
                { "com.apple.android.music", "Apple Music" },
                
                // 购物应用
                { "com.taobao.taobao", "淘宝" },
                { "com.tmall.wireless", "天猫" },
                { "com.jingdong.app.mall", "京东" },
                { "com.suning.mobile.ebuy", "苏宁易购" },
                { "com.amazon.mShop.android.shopping", "Amazon购物" },
                { "com.xunmeng.pinduoduo", "拼多多" },
                { "com.dangdang.buy2", "当当" },
                
                // 出行地图
                { "com.baidu.BaiduMap", "百度地图" },
                { "com.autonavi.minimap", "高德地图" },
                { "com.google.android.apps.maps", "Google Maps" },
                { "com.sdu.didi.psnger", "滴滴出行" },
                { "com.tencent.map", "腾讯地图" },
                
                // 支付金融
                { "com.eg.android.AlipayGphone", "支付宝" },
                { "com.tencent.mobilebank", "微信支付" },
                { "com.unionpay", "云闪付" },
                
                // Google服务
                { "com.google.android.gm", "Gmail" },
                { "com.google.android.googlequicksearchbox", "Google搜索" },
                { "com.google.android.apps.photos", "Google相册" },
                { "com.google.android.apps.docs", "Google文档" },
                { "com.google.android.talk", "Hangouts" },
                { "com.google.android.apps.translate", "Google翻译" },
                
                // 办公学习
                { "com.microsoft.office.word", "Word" },
                { "com.microsoft.office.excel", "Excel" },
                { "com.microsoft.office.powerpoint", "PowerPoint" },
                { "com.kingsoft.moffice_eng", "WPS Office" },
                { "cn.wps.moffice_eng", "WPS Office" },
                { "com.adobe.reader", "Adobe Reader" },
                { "com.duolingo", "多邻国" },
                
                // 工具应用
                { "com.cleanmaster.mguard", "猎豹清理大师" },
                { "com.qihoo360.mobilesafe", "360手机卫士" },
                { "com.tencent.qqpimsecure", "腾讯手机管家" },
                { "com.UCMobile.intl", "UC浏览器国际版" },
                
                // 游戏
                { "com.tencent.tmgp.sgame", "王者荣耀" },
                { "com.tencent.ig", "绝地求生" },
                { "com.netease.my", "我的世界" },
                { "com.mojang.minecraftpe", "Minecraft" },
                
                // 其他常用
                { "com.ximalaya.ting.android", "喜马拉雅" },
                { "com.sankuai.meituan", "美团" },
                { "me.ele.android", "饿了么" },
                { "com.ss.android.article.news", "今日头条" },
                { "com.zhihu.android", "知乎" }
            };

            if (friendlyNames.ContainsKey(packageName))
            {
                return friendlyNames[packageName];
            }

            // 如果没有映射，尝试从包名推断友好名称
            if (packageName.Contains("."))
            {
                string[] parts = packageName.Split('.');
                string lastPart = parts[parts.Length - 1];
                
                // 简单的名称美化
                if (lastPart.Length > 2)
                {
                    return char.ToUpper(lastPart[0]) + lastPart.Substring(1);
                }
            }

            return packageName;
        }

        /// <summary>
        /// 验证虚拟显示分辨率格式是否正确
        /// </summary>
        /// <param name="resolution">分辨率字符串</param>
        /// <returns>格式是否正确</returns>
        private bool IsValidResolution(string resolution)
        {
            // 空值是允许的，表示使用主显示的尺寸和密度
            if (string.IsNullOrWhiteSpace(resolution))
                return true;

            // 支持格式: 
            // 1. 空值 (使用主显示的尺寸和密度)
            // 2. WIDTHxHEIGHT (如: 1920x1080)
            // 3. WIDTHxHEIGHT/DPI (如: 1920x1080/420)
            // 4. /DPI (如: /240，使用主显示尺寸，指定DPI)
            var patterns = new[]
            {
                @"^\d+x\d+$",           // 1920x1080
                @"^\d+x\d+/\d+$",       // 1920x1080/420
                @"^/\d+$"               // /240 (使用主显示尺寸，指定DPI)
            };
            
            return patterns.Any(pattern => Regex.IsMatch(resolution.Trim(), pattern));
        }
    }
}
